/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { Request, Response } from 'express';

// 统一响应选项
export interface ResponseItem {
  code: number;
  msg: string;
  data: object | Array<any> | string;
}

// 重置内容
export interface optsParamsType {
  msg?: string;
  data?: object | Array<any> | string;
  wait?: number | string;
}

// 成功响应
export const responseSuccess = async (req: Request, res: Response, opts: optsParamsType = {}) => {
  const { wait, ...rest } = opts;
  await waitTime(wait);
  res.send({
    code: 0,
    msg: 'success',
    data: {},
    ...rest,
  });
};
// 失败响应
export const responseFail = async (req: Request, res: Response, opts: optsParamsType = {}) => {
  const { wait, ...rest } = opts;
  await waitTime(wait);
  res.send({
    code: 99,
    msg: 'fail',
    data: {},
    ...rest,
  });
};

// 随机响应失败或成功
export const responseRandom = (req: Request, res: Response, opts: optsParamsType) =>
  Math.floor((Math.random() * 2) % 2)
    ? responseSuccess(req, res, opts)
    : responseFail(req, res, opts);

// 随机时间
export const randomTimer = (time: number | string): number => {
  const list = [0, 500, 2000];
  return typeof time === 'number' ? time : list[Math.floor(Math.random() * list.length)];
};

// 延迟执行
export const waitTime = (time: number | string = 'auto') => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, randomTimer(time));
  });
};
